package com.servicesystem.servicesystem.config;

import com.servicesystem.servicesystem.service.UserAliService;
import com.servicesystem.servicesystem.untis.token.GenerateTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class DefaultSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private DefaultUserDetailsService defaultUserDetailsService;
    @Autowired
    private UserAliService userAliService;

    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(defaultUserDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
        http.authorizeRequests().antMatchers("/", "/login", "/swagger-ui.html/**", "/message/message-receiver").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(
                        new BeforeLoginFilter(new GenerateTokenUtils()
                                , authenticationManager()
                                , userAliService), UsernamePasswordAuthenticationFilter.class)
                .addFilter(new LoginFilter(new GenerateTokenUtils(), authenticationManager()))
                .exceptionHandling().authenticationEntryPoint(new Http401AuthenticationEntryPoint());
    }
}
